<?php

class AbstractAssociationElement extends AbstractSelectionElement
{

  public $assocTable;

  public $assocPrimaryKey;

  public $assocForeignKey;

  public function getAssocTable()
  {
    if (empty($this->assocTable)) {
      $tables = array($this->form->table, $this->getTable());

      sort($tables);

      $this->assocTable = implode('_', $tables);
    }

    return $this->assocTable;
  }

  public function getAssocPrimaryKey()
  {
    if (empty($this->assocPrimaryKey)) {
      $this->assocPrimaryKey = $this->getField();
    }

    return $this->assocPrimaryKey;
  }

  public function getAssocForeignKey()
  {
    if (empty($this->assocForeignKey)) {
      $this->assocForeignKey = $this->getKeyField();
    }

    return $this->assocForeignKey;
  }

  public function getValues(&$row)
  {
    $id = $this->getValue($row);

    $at = $this->getAssocTable();
    $apk = $this->getAssocPrimaryKey();
    $afk = $this->getAssocForeignKey();

    $query = DB::getInstance()->query()->from($at)->select($afk)->where("$apk = ?");

    $data = $query->execute($id);

    $data = $data->fetchCol();

    return $data;
  }

}
